﻿using System;
using System.Globalization;
using System.Reflection;

namespace zijian666.AnyExtensions.Privates;

internal class StringComparerFactory
{
    public static StringComparer Create(CompareOptions options, CultureInfo? culture = null)
    {
        culture ??= CultureInfo.CurrentCulture;
#if NETSTANDARD2_0_OR_GREATER || NET7_0_OR_GREATER
        return culture.CompareInfo.GetStringComparer(options);
#else
        var type = typeof(string).Assembly.GetType("System.CultureAwareComparer", false, false)
                    ?? throw new NotImplementedException("无法获取系统类型 System.CultureAwareComparer");
        var flags = BindingFlags.Instance | BindingFlags.NonPublic;
        var ctor = type.GetConstructor(flags, null, [typeof(CompareInfo), typeof(CompareOptions)], null)
                    ?? throw new TypeInitializationException("System.CultureAwareComparer", new MissingMethodException("System.CultureAwareComparer", ".ctor"));
        return (StringComparer)ctor.Invoke([culture.CompareInfo, options]);
#endif
    }
}
